#!/bin/bash

ORIGPATH=$PATH
DIRCMD=0

finish()
{
  PATH=$ORIGPATH
}

buildFailed ()
{
  echo "ERROR: Build failed..."
  finish
  exit $1
}

command=$0
if [ "$1" == "-E" ] || [ "$1" == "-N" ] || [ "$1" == "-C" ] || [ "$1" == "-I" ]; then
  test_mode=$1
  shift
else
  test_mode="-E"
fi

test_track=""
individual_test=""
while [ "${1:-}" != "" ]; do
  case "$1" in
    "--test")
      shift
      individial_test=$1
      ;;
    "--track")
      shift
      test_track="--track \"$1\""
      ;;
  esac
  shift
done

if [ "$test_mode" == "" ] || [ "$test_mode" == "-E" ]; then
  "@CMAKE_COMMAND@" --build . --config Release
  errorVal=$?
  if [ "$?" == 1 ]; then
    buildFailed $errorVal
  fi
  "@CMAKE_CTEST_COMMAND@" -C Release -D Experimental --output-on-failure $test_track
fi

if [ "$test_mode" == "-N" ]; then
   # Clean before the nightly build to enforce all build warnings appear on all nightly dashboard submissions
  "@CMAKE_COMMAND@" --build . --config Release --clean-first
  "@CMAKE_CTEST_COMMAND@" -C Release -D Nightly $test_track
fi

if [ "$test_mode" == "-C" ]; then
  "@CMAKE_CTEST_COMMAND@" -C Release -D Continuous $test_track
  # Wait for some time before continue to allow checking the results of the executions
  sleep 15
fi

if [ "$test_mode" == "-I" ]; then
  # Run individual tests with regexp search
  # Display the list of tests
  "@CMAKE_CTEST_COMMAND@" -R "$individual_test" -N -C Release
  # Run selected tests
  "@CMAKE_CTEST_COMMAND@" -R "$individual_test" -V -C Release
fi

finish
echo "DONE"
